package com.atguigu.demo;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author 孔德成
 * @Slogan 致敬大师，致敬未来的你
 * @date 2021/8/8
 */
public class SaleTicketDemo {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(() -> {
            for (int i = 0; i < 51; i++) ticket.sale();
        }, "张三").start();
        new Thread(() -> {
            for (int i = 0; i < 51; i++) ticket.sale();
        }, "王五").start();
        new Thread(() -> {
            for (int i = 0; i < 51; i++) ticket.sale();
        }, "赵四").start();

    }

    private static class Ticket {

        private final ReentrantLock lock = new ReentrantLock();

        int number = 50;

        public void sale() {
            lock.lock();
            try {
                if (number > 0) {
                    System.out.println(Thread.currentThread().getName() + "\t卖出了第" + (50 - number + 1) + "张票,还剩" + --number + "张票");
                }
            } finally {
                lock.unlock();
            }

        }
    }
}
